import kkConfig from 'kkConfig'
import kk from 'kokos'

cc.Class({
    extends: cc.Component,

    onLoad() {
        kk.adapt()
        this.canvas = cc.find('Canvas')

        this.playLoadingAnimation()

        if (kk.cache.isFirstLoading) {
            this.gameInit()
        } else {
            this.loadNextScene()
        }
    },

    start() {

    },

    // 只在开始时执行一次的初始化操作
    gameInit() {
        this.showHealthAdvice()
        kk.baseData.loadPlayerData()
            .then(() => {
                const sceneName = kkConfig.firstScene
                cc.director.preloadScene(sceneName, () => {
                    // cc.log('场景预加载完成，进入场景 ->')
                    cc.director.loadScene(sceneName)
                })
            })
    },

    // 加载下一个场景
    loadNextScene() {
        const sceneName = kk.cache.nextScene
        cc.director.preloadScene(sceneName, () => {
            setTimeout(() => {
                // cc.log('场景预加载完成，进入场景 ->')
                cc.director.loadScene(sceneName)
            }, 0.5 * 1000)
        })
    },

    // 显示健康忠告
    showHealthAdvice() {
        if (kkConfig.healthAdvice.isShow && kk.cache.isFirstLoading) {
            const fadeOutTimeS = 0.5 // 健康忠告渐隐动画的时长
            const panel = this.canvas.getChildByName('healthAdvice')
            panel.active = true

            if (kkConfig.healthAdvice.showTimeS - fadeOutTimeS < 0) {
                throw new Error('渐隐时间不能大于健康忠告播放时间')
            }

            this.scheduleOnce(() => {
                const outAction = cc.fadeOut(fadeOutTimeS)
                panel.runAction(outAction)
                this.scheduleOnce(() => {
                    panel.active = false
                }, fadeOutTimeS)
            }, kkConfig.healthAdvice.showTimeS - fadeOutTimeS)
        }
    },

    // 播放加载中的动画
    playLoadingAnimation() {
        const animationSpeed = 0.3 // 动画速度 0.3 秒刷新一次
        const label = this.canvas.getChildByName('loadingString').getComponent(cc.Label)
        let baseDesc = '加载中'
        let count = 1

        this.schedule(() => {
            let dot = ''
            for (let i = 0; i < count % 5; i++) {
                dot += '.'
            }
            label.string = baseDesc + dot
            count++
        }, animationSpeed)
    }

    // update (dt) {},
});
